package com.erp.service.entity;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.protocol.HTTP;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * Created by gxchen on 2015/12/3.
 */
public class ResponsedResult {
    /**
     * 通用返回结果接口
     * @author ccl
     */
        private final static String TAG = "ResponsedResult";

        protected HttpResponse httpResponse;

        protected HttpUriRequest httpUriRequest;
        public ResponsedResult(HttpResponse httpResponse,
                               HttpUriRequest httpUriRequest) {
            this.httpResponse = httpResponse;
            this.httpUriRequest = httpUriRequest;
        }

        /**
         * 获取结果的响应对象
         *
         * @return
         */
        public HttpResponse getHttpResponse() {
            return httpResponse;
        }

        public void close() {
            if (httpUriRequest != null)
                httpUriRequest.abort();
        }

        /**
         * 获取返回的字符串
         */
        @Override
        public String toString() {
            try {
                String result = retrieveInputStream(httpResponse.getEntity());
                return result;
            } finally {
                if (httpUriRequest != null)
                    httpUriRequest.abort();
            }

        }

        /**
         * 获取响应的输入流
         *
         * @return
         * @throws IllegalStateException
         * @throws java.io.IOException
         */
        public InputStream getInputStream() throws IllegalStateException,
                IOException {
            return httpResponse.getEntity().getContent();
        }

        /**
         * 处理httpResponse信息,返回String
         *
         * @param httpEntity
         * @return String
         */
        protected String retrieveInputStream(HttpEntity httpEntity) {
            int length = (int) httpEntity.getContentLength();
            if (length < 0)
                length = 10000;
            StringBuffer stringBuffer = new StringBuffer(length);
            try {
                InputStreamReader inputStreamReader = new InputStreamReader(
                        httpEntity.getContent(), HTTP.UTF_8);
                char buffer[] = new char[length];
                int count;
                if (length > 0) {
                    while ((count = inputStreamReader.read(buffer, 0, length)) > 0) {
                        stringBuffer.append(buffer, 0, count);
                    }
                }
            } catch (UnsupportedEncodingException e) {
            } catch (IllegalStateException e) {
            } catch (IOException e) {
            }
            return stringBuffer.toString();
        }

}
